<?
/* @author Udo Schroeter <udo.schroeter@gmail.com>
 * @license dual license: LGPL / commercial use license
 */ 

function iplimits_check($ip)
{
  global $config;
  $ipLog = DB_GetDataset('iplog', $ip, 'ip_address');
  $today = date('Y-m-d H:i:s');
  $blockLimit = getDefault($config['iplimits']['daily_limit'], 10000);
  if ($ipLog['ip_ignore'] != 'Y')
  {

    if (sizeof($ipLog) > 0)
    {
      $lastADay = $ipLog['ip_lastaccess'];
      $lastADay = CutSegment(' ', $lastADay);
      
      $config['iplimits']['lastpost'] = parse_timestamp($ipLog['ip_lastpost']);
      $config['iplimits']['lastpostsec'] = time()-$config['iplimits']['lastpost'];
      
      if ($lastADay != date('Y-m-d'))
      {
        $ipLog['ip_used'] = 0;
      }
      
      if ($ipLog['ip_used'] > $blockLimit || $ipLog['ip_banned'] == 'Y')
      {
        $ipLog['ip_blocked'] = $ipLog['ip_blocked']+1;
        $blockThis = true; 
      }
      else
      {
        $ipLog['ip_used'] = $ipLog['ip_used']+1;
      }
        
      $ipLog['ip_lastaccess'] = $today;
    }
    else
    {
      $ipLog['ip_address'] = $ip;
      $ipLog['ip_lastaccess'] = $today;
      $ipLog['ip_used'] = '1';
    }

    $config['iplimits']['ds'] = $ipLog;
    DB_UpdateDataset('iplog', $ipLog);

    if ($blockThis)
    {
      banner('Your IP address is blocked due to excessive traffic.');
      die();
    }
    
  }
}

function iplimits_ban($ip)
{
  $ds = DB_GetDataset('iplog', $ip, 'ip_address');
  $ds['ip_address'] = $ip;
  $ds['ip_banned'] = 'Y';
  $ds['ip_ignore'] = 'Y';
  DB_UpdateDataset('iplog', $ds);
}

function iplimits_post($minDelayInSeconds = 30)
{
  global $config;
  if ($config['iplimits']['lastpostsec'] < $minDelayInSeconds)
  {
    return(false);
  }
  else
  {
    $config['iplimits']['ds']['ip_lastpost'] = date('Y-m-d H:i:s');
    DB_UpdateDataset('iplog', $config['iplimits']['ds']);
    return(true);
  }
}

iplimits_check($_SERVER['REMOTE_ADDR']);

?>